<template>
  <div class="budget-config-container">
    <el-card shadow="hover" class="page-card">
      <template #header>
        <div class="card-header">
          <span class="page-title">预算配置管理</span>
        </div>
      </template>

      <!-- 预算分析图表区域 -->
      <div class="charts-section">
        <el-card class="chart-card">
          <template #header>
            <div class="card-header">
              <span>各部门预算金额分布</span>
            </div>
          </template>
          <VChart 
            class="chart" 
            :option="departmentChartOption" 
            autoresize 
          />
        </el-card>
        <el-card class="chart-card">
          <template #header>
            <div class="card-header">
              <span>各成本项目预算金额分布</span>
            </div>
          </template>
          <VChart 
            class="chart" 
            :option="costItemChartOption" 
            autoresize 
          />
        </el-card>
      </div>

      <!-- 筛选搜索区域 -->
      <div class="search-section">
        <el-form :inline="true" :model="searchForm" class="search-form">
          <el-form-item label="年份">
            <el-select style="width: 120px;" v-model="searchForm.year" placeholder="请选择年份">
              <el-option v-for="option in yearOptions" :key="option.value" :label="option.label"
                :value="option.value" />
            </el-select>
          </el-form-item>
          <el-form-item label="部门">
            <el-select style="width: 120px;" v-model="searchForm.departmentId" placeholder="请选择部门">
              <el-option v-for="option in departmentOptions" :key="option.value" :label="option.label"
                :value="option.value" />
            </el-select>
          </el-form-item>
          <el-form-item label="成本项目">
            <el-select style="width: 120px;" v-model="searchForm.costItemId" placeholder="请选择成本项目">
              <el-option v-for="option in costItemOptions" :key="option.value" :label="option.label"
                :value="option.value" />
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="enhancedHandleSearch">搜索</el-button>
            <el-button @click="handleReset">重置</el-button>
          </el-form-item>
        </el-form>
        <!-- 操作按钮区域 -->
        <div class="action-section">
          <el-button type="primary" @click="handleAdd">新增预算配置</el-button>
        </div>
      </div>



      <!-- 数据列表区域 -->
      <div class="table-section">
        <el-table v-loading="loading" :data="budgetConfigs" style="width: 100%" border>
          <el-table-column prop="id" label="ID" width="80" />
          <el-table-column prop="departmentName" label="部门" width="120" />
          <el-table-column prop="costItemName" label="成本项目" width="150" />
          <el-table-column prop="year" label="年份" width="100" />
          <el-table-column prop="budgetAmount" label="预算金额" width="150">
            <template #default="scope">
              {{ formatCurrency(scope.row.budgetAmount) }}
            </template>
          </el-table-column>
          <el-table-column prop="remark" label="备注" show-overflow-tooltip />
          <el-table-column label="操作" fixed="right">
            <template #default="scope">
              <el-button type="primary" size="small" @click="handleEdit(scope.row)">编辑</el-button>
              <el-button type="danger" size="small" @click="handleDelete(scope.row)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>

        <!-- 分页组件 -->
        <div class="pagination-section">
          <el-pagination v-model:current-page="pagination.currentPage" v-model:page-size="pagination.pageSize"
            :page-sizes="[2, 10, 20, 50, 100]" layout="total, sizes, prev, pager, next, jumper" :total="pagination.total"
            @size-change="handlePageChange" @current-change="handlePageChange" />
        </div>
      </div>

      <!-- 编辑对话框 -->
      <el-dialog v-model="dialogVisible" :title="dialogTitle" width="500px" destroy-on-close>
        <el-form ref="formRef" :model="formData" :rules="formRules" label-width="100px" class="dialog-form">
          <el-form-item label="年份" prop="year">
            <el-select v-model="formData.year" placeholder="请选择年份">
              <el-option v-for="option in yearOptions" :key="option.value" :label="option.label"
                :value="option.value" />
            </el-select>
          </el-form-item>
          <el-form-item label="部门" prop="departmentId">
            <el-select v-model="formData.departmentId" placeholder="请选择部门">
              <el-option v-for="option in departmentOptions" :key="option.value" :label="option.label"
                :value="option.value" />
            </el-select>
          </el-form-item>
          <el-form-item label="成本项目" prop="costItemId">
            <el-select v-model="formData.costItemId" placeholder="请选择成本项目">
              <el-option v-for="option in costItemOptions" :key="option.value" :label="option.label"
                :value="option.value" />
            </el-select>
          </el-form-item>
          <el-form-item label="预算金额" prop="budgetAmount">
            <el-input-number v-model.number="formData.budgetAmount" :min="0.01" :step="0.01" style="width: 100%"
              placeholder="请输入预算金额" />
          </el-form-item>
          <el-form-item label="备注" prop="remark">
            <el-input v-model="formData.remark" type="textarea" placeholder="请输入备注信息" :rows="3" />
          </el-form-item>
        </el-form>
        <template #footer>
          <span class="dialog-footer">
            <el-button @click="dialogVisible = false">取消</el-button>
            <el-button type="primary" @click="handleSubmit">确定</el-button>
          </span>
        </template>
      </el-dialog>
    </el-card>
  </div>
</template>

<script setup>
import { ref, computed, onMounted, onMounted as VueOnMounted } from 'vue';
import { use } from 'echarts/core';
import { CanvasRenderer } from 'echarts/renderers';
import { BarChart } from 'echarts/charts';
import { GridComponent, TooltipComponent, TitleComponent, LegendComponent } from 'echarts/components';
import VChart from 'vue-echarts';

import useBudgetConfig from '@/hooks/useBudgetConfig';
import { ElMessageBox } from 'element-plus';
import budgetConfigApi from '@/apis/budgetConfig';

// 注册 ECharts 组件
use([CanvasRenderer, BarChart, GridComponent, TooltipComponent, TitleComponent, LegendComponent]);



// 从 hook 中解构所需的变量和方法
const {
  loading,
  dialogVisible,
  dialogTitle,
  formRef,
  budgetConfigs,

  searchForm,
  pagination,
  formData,
  formRules,
  departmentOptions,
  costItemOptions,
  yearOptions,
  handleView: handleViewData,
  handleEdit: handleEditData,
  handleAdd,
  handleSubmit,
  handleDelete: handleDeleteData,
  handleSearch,
  handleReset,
  handlePageChange,
  init
} = useBudgetConfig();

// 格式化货币
const formatCurrency = (value) => {
  // 处理null、undefined或空字符串
  if (value === null || value === undefined || value === '') {
    return '¥ 0.00';
  }
  // 转换为数字并确保是有效数字
  const numValue = Number(value);
  if (typeof numValue !== 'number' || isNaN(numValue)) {
    return '¥ 0.00';
  }
  return `¥ ${numValue.toLocaleString('zh-CN', { minimumFractionDigits: 2, maximumFractionDigits: 2 })}`;
};

// 处理查看
const handleView = (row) => {
  handleViewData(row);
};

// 处理编辑
const handleEdit = (row) => {
  handleEditData(row);
};

// 处理删除
const handleDelete = (row) => {
  // 直接调用hook中的handleDeleteData，那里已经实现了名称查找逻辑
  handleDeleteData(row);
};



// 图表配置
const departmentChartOption = ref({
  title: {
    text: '',
    left: 'center'
  },
  tooltip: {
    trigger: 'axis',
    formatter: function(params) {
      const data = params[0];
      return `${data.name}<br/>预算金额: ¥${(data.value).toLocaleString('zh-CN', { minimumFractionDigits: 2, maximumFractionDigits: 2 })}`;
    }
  },
  xAxis: {
    type: 'category',
    data: [],
    axisLabel: {
      rotate: 45
    }
  },
  yAxis: {
    type: 'value',
    axisLabel: {
      formatter: function(value) {
        return (value / 10000).toFixed(0) + '万';
      }
    }
  },
  series: [{
    data: [],
    type: 'bar',
    itemStyle: {
      color: new URLSearchParams(window.location.search).get('dark') ? '#409EFF' : '#409EFF'
    }
  }]
});

const costItemChartOption = ref({
  title: {
    text: '',
    left: 'center'
  },
  tooltip: {
    trigger: 'axis',
    formatter: function(params) {
      const data = params[0];
      return `${data.name}<br/>预算金额: ¥${(data.value).toLocaleString('zh-CN', { minimumFractionDigits: 2, maximumFractionDigits: 2 })}`;
    }
  },
  xAxis: {
    type: 'category',
    data: [],
    axisLabel: {
      rotate: 45
    }
  },
  yAxis: {
    type: 'value',
    axisLabel: {
      formatter: function(value) {
        return (value / 10000).toFixed(0) + '万';
      }
    }
  },
  series: [{
    data: [],
    type: 'bar',
    itemStyle: {
      color: new URLSearchParams(window.location.search).get('dark') ? '#67C23A' : '#67C23A'
    }
  }]
});

// 获取预算分析数据
const fetchBudgetAnalysis = async () => {
  try {
    // 使用当前搜索表单中的年份，如果没有则使用当前年份
    const year = searchForm.year ? parseInt(searchForm.year) : new Date().getFullYear();
    
    // 调用API获取分析数据
    const response = await budgetConfigApi.getBudgetAnalysis({ year });
    
    if (response && response.data) {
      const analysisData = response.data;
      
      // 更新部门预算图表数据
      if (analysisData.departmentAnalysis && Array.isArray(analysisData.departmentAnalysis)) {
        const departmentNames = analysisData.departmentAnalysis.map(item => item.name || '未知部门');
        const departmentValues = analysisData.departmentAnalysis.map(item => {
          // 确保value是数字
          const value = item.value;
          return typeof value === 'number' ? value : parseFloat(value) || 0;
        });
        
        departmentChartOption.value.xAxis.data = departmentNames;
        departmentChartOption.value.series[0].data = departmentValues;
      }
      
      // 更新成本项目预算图表数据
      if (analysisData.costItemAnalysis && Array.isArray(analysisData.costItemAnalysis)) {
        const costItemNames = analysisData.costItemAnalysis.map(item => item.name || '未知项目');
        const costItemValues = analysisData.costItemAnalysis.map(item => {
          // 确保value是数字
          const value = item.value;
          return typeof value === 'number' ? value : parseFloat(value) || 0;
        });
        
        costItemChartOption.value.xAxis.data = costItemNames;
        costItemChartOption.value.series[0].data = costItemValues;
      }
    }
  } catch (error) {
    console.error('获取预算分析数据失败:', error);
    // 如果获取失败，使用默认模拟数据
    departmentChartOption.value.xAxis.data = ['技术部', '市场部', '财务部', '人力资源部', '行政部', '销售部', '客服部', '产品部'];
    departmentChartOption.value.series[0].data = [306624.33, 808946.88, 442780.78, 996945.83, 817510.09, 773070.81, 183218.12, 858806.55];
    
    costItemChartOption.value.xAxis.data = ['工资薪金', '办公设备', '差旅费', '会议费', '培训费', '水电费', '通讯费', '材料费', '广告费', '招待费'];
    costItemChartOption.value.series[0].data = [200000, 150000, 120000, 100000, 90000, 80000, 70000, 60000, 50000, 40000];
  }
};

// 组件挂载时初始化数据
onMounted(async () => {
  init();
  await fetchBudgetAnalysis();
});

// 在搜索按钮点击时也更新图表数据
const enhancedHandleSearch = async () => {
  handleSearch();
  await fetchBudgetAnalysis();
};
</script>

<style scoped>
.budget-config-container {
  padding: 20px;
  background-color: #f5f7fa;
  min-height: 100vh;
}

.page-card {
  margin: 0;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  border-radius: 8px;
  overflow: hidden;
  transition: all 0.3s ease;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 0;
}

.page-title {
  font-size: 18px;
  font-weight: bold;
  color: #303133;
  margin: 0;
}



.charts-section {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(500px, 1fr));
  gap: 20px;
  margin-bottom: 20px;
}

.chart-card {
  background: #fff;
  border-radius: 8px;
  overflow: hidden;
  box-shadow: 0 1px 4px rgba(0, 0, 0, 0.05);
}

.chart {
  height: 400px;
  width: 100%;
}

.search-section {
  margin-bottom: 20px;
  padding: 20px;
  background: #fff;
  border-radius: 8px;
  box-shadow: 0 1px 4px rgba(0, 0, 0, 0.05);
}

.search-form {
  background: transparent;
  padding: 0;
}

.search-form .el-form-item {
  margin-bottom: 0;
  margin-right: 15px;
}

.search-form .el-form-item__label {
  font-size: 14px;
  color: #606266;
}

.action-section {
  margin-bottom: 20px;
  text-align: right;
  padding: 0 20px 20px 20px;
}

.action-section .el-button {
  transition: all 0.3s ease;
}

.action-section .el-button:hover {
  transform: translateY(-1px);
  box-shadow: 0 2px 8px rgba(64, 158, 255, 0.3);
}

.table-section {
  margin-top: 0;
  background: #fff;
  border-radius: 8px;
  box-shadow: 0 1px 4px rgba(0, 0, 0, 0.05);
  overflow: hidden;
}

/* 表格样式优化 */
.el-table {
  border: none;
  border-radius: 8px;
  overflow: hidden;
}

.el-table--border th,
.el-table--border td {
  border-right: 1px solid #ebeef5;
}

.el-table--border th:last-child,
.el-table--border td:last-child {
  border-right: none;
}

.el-table::before {
  height: 0;
}

.el-table th {
  background-color: #fafafa;
  font-weight: 500;
  color: #606266;
  font-size: 14px;
  border-bottom: 1px solid #ebeef5;
}

.el-table td {
  font-size: 14px;
  color: #303133;
  border-bottom: 1px solid #ebeef5;
}

.el-table tr:hover>td {
  background-color: #f5f7fa !important;
}

/* 表格操作按钮样式 */
.el-table .el-button {
  margin: 0 5px;
  transition: all 0.3s ease;
}

.el-table .el-button:hover {
  transform: translateY(-1px);
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.12);
}

/* 分页样式 */
.pagination-section {
  margin-top: 0;
  padding: 15px 20px;
  display: flex;
  justify-content: flex-end;
  background: #fff;
  border-top: 1px solid #ebeef5;
}

.el-pagination {
  font-size: 14px;
}

/* 对话框样式优化 */
.el-dialog {
  border-radius: 8px;
  overflow: hidden;
}

.el-dialog__header {
  background-color: #fafafa;
  border-bottom: 1px solid #ebeef5;
  padding: 20px 20px 10px 20px;
}

.el-dialog__title {
  font-size: 16px;
  font-weight: 500;
  color: #303133;
}

.el-dialog__body {
  padding: 25px;
}

.dialog-form {
  max-height: 60vh;
  overflow-y: auto;
}

.dialog-form .el-form-item {
  margin-bottom: 20px;
}

.dialog-form .el-form-item__label {
  font-size: 14px;
  color: #606266;
  font-weight: 500;
}

.dialog-footer {
  text-align: right;
  padding-top: 15px;
  border-top: 1px solid #ebeef5;
}

.dialog-footer .el-button {
  margin-left: 10px;
  transition: all 0.3s ease;
}

.dialog-footer .el-button:hover {
  transform: translateY(-1px);
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.12);
}

/* 加载状态样式 */
.el-loading-mask {
  border-radius: 8px;
}

.el-loading-spinner {
  top: calc(50% - 40px);
}

/* 空状态样式优化 */
.el-empty {
  padding: 50px 0;
}

/* 滚动条样式 */
.dialog-form::-webkit-scrollbar,
.el-table__body-wrapper::-webkit-scrollbar {
  width: 6px;
}

.dialog-form::-webkit-scrollbar-track,
.el-table__body-wrapper::-webkit-scrollbar-track {
  background: #f1f1f1;
}

.dialog-form::-webkit-scrollbar-thumb,
.el-table__body-wrapper::-webkit-scrollbar-thumb {
  background: #ccc;
  border-radius: 3px;
}

.dialog-form::-webkit-scrollbar-thumb:hover,
.el-table__body-wrapper::-webkit-scrollbar-thumb:hover {
  background: #999;
}

/* 响应式设计 */

@media (max-width: 768px) {
  .budget-config-container {
    padding: 10px;
  }

  .charts-section {
    grid-template-columns: 1fr;
  }

  .chart {
    height: 300px;
  }

  .search-section,
  .action-section {
    padding: 15px;
  }

  .search-form {
    display: flex;
    flex-direction: column;
  }

  .search-form .el-form-item {
    margin-right: 0;
    margin-bottom: 10px;
  }

  .el-table {
    font-size: 12px;
  }

  .el-table .el-button {
    padding: 4px 8px;
    font-size: 12px;
    margin: 0 2px;
  }

  .dialog-form {
    max-height: 70vh;
  }
}
</style>